import { router,addMyRouters } from '@/router/index.js'
import { getToken } from '@/utils/token.js'
import { failed } from '@/utils/messageUtils.js';
import { useCookies } from '@vueuse/integrations/useCookies'
import store from '@/store/index.js'

// 需不需要重新获取信息
let hasGetUserInfo = false;
router.beforeEach(async (to, from, next) => {
    // 把上一次的路由存储在cookie中
    const cookie = useCookies()
    cookie.set("fromURL", from.path)
    const token = getToken();
    // 没有登录，强制转回登录页面
    if (!token && to.path !== '/login') {
        failed("未登录，强制转回登录页面")
        return next({ path: '/login' })
    }
    // 用户登陆了，获取用户信息，存储在vuex中
    let hasNewRoutes  = false
    if(token && !hasGetUserInfo && to.path !== '/login'){
        let res = await store.dispatch("getUserInfo")
        hasGetUserInfo = true;
        hasNewRoutes = addMyRouters(res.data.routerList)
    }
    if(!token){
        hasGetUserInfo = false;
    }
    hasNewRoutes ? next(to.path) : next()
})